<template>
  <view class="register-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
    </view>
    
    <!-- 注册表单 -->
    <view class="register-form">
      <!-- 标题区域 -->
      <view class="title-section">
        <text class="title">注册账号</text>
        <text class="subtitle">创建您的魔方训练账号</text>
      </view>
      
      <!-- 表单区域 -->
      <view class="form-section">
        <view class="form-item">
          <view class="input-wrapper">
            <text class="icon">📱</text>
            <input 
              class="input" 
              type="number" 
              placeholder="请输入手机号" 
              v-model="formData.phone"
              maxlength="11"
              @input="validatePhone"
            />
          </view>
          <text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>
        </view>
        
        <view class="form-item">
          <view class="input-wrapper">
            <text class="icon">🔐</text>
            <input 
              class="input" 
              type="number" 
              placeholder="请输入验证码" 
              v-model="formData.code"
              maxlength="4"
              @input="validateCode"
            />
            <button 
              class="code-btn" 
              :class="{ 'disabled': !canSendCode || codeSending }"
              :disabled="!canSendCode || codeSending"
              @click="sendCode"
            >
              {{ codeSending ? '发送中...' : codeText }}
            </button>
          </view>
          <text v-if="errors.code" class="error-text">{{ errors.code }}</text>
        </view>
        
        <view class="form-item">
          <view class="input-wrapper">
            <text class="icon">🔒</text>
            <input 
              class="input" 
              :type="showPassword ? 'text' : 'password'" 
              placeholder="请设置密码（至少6位）" 
              v-model="formData.password"
              @input="validatePassword"
            />
            <text 
              class="password-toggle" 
              @click="togglePassword"
            >
              {{ showPassword ? '👁️' : '👁️‍🗨️' }}
            </text>
          </view>
          <text v-if="errors.password" class="error-text">{{ errors.password }}</text>
        </view>
        
        <view class="form-item">
          <view class="input-wrapper">
            <text class="icon">🔒</text>
            <input 
              class="input" 
              :type="showConfirmPassword ? 'text' : 'password'" 
              placeholder="请确认密码" 
              v-model="formData.confirmPassword"
              @input="validateConfirmPassword"
            />
            <text 
              class="password-toggle" 
              @click="toggleConfirmPassword"
            >
              {{ showConfirmPassword ? '👁️' : '👁️‍🗨️' }}
            </text>
          </view>
          <text v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</text>
        </view>
        
        <!-- 注册按钮 -->
        <button 
          class="register-btn" 
          :class="{ 'disabled': !isFormValid || loading }"
          :disabled="!isFormValid || loading"
          @click="handleRegister"
        >
          <text v-if="loading" class="loading-text">注册中...</text>
          <text v-else>注册</text>
        </button>
        
        <!-- 底部链接 -->
        <view class="bottom-links">
          <text class="link" @click="goToLogin">已有账号？去登录</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { AccountAPI, SmsAPI } from '@/api/user.js'
import { setToken, setUserInfo } from '@/utils/auth'

// 响应式数据
const loading = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const codeSending = ref(false)
const countdown = ref(0)

// 表单数据
const formData = reactive({
  phone: '',
  code: '',
  password: '',
  confirmPassword: ''
})

// 错误信息
const errors = reactive({
  phone: '',
  code: '',
  password: '',
  confirmPassword: ''
})

// 表单验证
const validatePhone = () => {
  const phone = formData.phone
  if (!phone) {
    errors.phone = '请输入手机号'
    return false
  }
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    errors.phone = '请输入正确的手机号'
    return false
  }
  errors.phone = ''
  return true
}

const validateCode = () => {
  const code = formData.code
  if (!code) {
    errors.code = '请输入验证码'
    return false
  }
  if (!/^\d{4}$/.test(code)) {
    errors.code = '验证码为4位数字'
    return false
  }
  errors.code = ''
  return true
}

const validatePassword = () => {
  const password = formData.password
  if (!password) {
    errors.password = '请输入密码'
    return false
  }
  if (password.length < 6) {
    errors.password = '密码长度不能少于6位'
    return false
  }
  errors.password = ''
  return true
}

const validateConfirmPassword = () => {
  const confirmPassword = formData.confirmPassword
  if (!confirmPassword) {
    errors.confirmPassword = '请确认密码'
    return false
  }
  if (confirmPassword !== formData.password) {
    errors.confirmPassword = '两次输入的密码不一致'
    return false
  }
  errors.confirmPassword = ''
  return true
}

// 是否可以发送验证码
const canSendCode = computed(() => {
  return formData.phone && !errors.phone && countdown.value === 0
})

// 验证码按钮文本
const codeText = computed(() => {
  return countdown.value > 0 ? `${countdown.value}s` : '发送验证码'
})

// 表单是否有效
const isFormValid = computed(() => {
  return formData.phone && formData.code && formData.password && formData.confirmPassword &&
         !errors.phone && !errors.code && !errors.password && !errors.confirmPassword
})

// 切换密码显示
const togglePassword = () => {
  showPassword.value = !showPassword.value
}

const toggleConfirmPassword = () => {
  showConfirmPassword.value = !showConfirmPassword.value
}

// 发送验证码
const sendCode = async () => {
  if (!canSendCode.value || codeSending.value) return
  
  // 验证手机号
  if (!validatePhone()) return
  
  codeSending.value = true
  
  try {
    const result = await SmsAPI.sendPhoneCode({ 
      phone: formData.phone,
      codeType: 1,
      type: 2
    })
    
    if (result.code === 0) {
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      })
      
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      uni.showToast({
        title: result.msg || '发送失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    uni.showToast({
      title: error.message || '发送验证码失败',
      icon: 'none'
    })
  } finally {
    codeSending.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  if (!isFormValid.value || loading.value) return
  
  // 验证表单
  const phoneValid = validatePhone()
  const codeValid = validateCode()
  const passwordValid = validatePassword()
  const confirmPasswordValid = validateConfirmPassword()
  
  if (!phoneValid || !codeValid || !passwordValid || !confirmPasswordValid) {
    return
  }
  
  loading.value = true
  
  try {
    // 1. 获取认证Token
    const authResult = await AccountAPI.getAuthToken({
      phone: formData.phone,
      accountType: 1,
      code: formData.code,
      codeType: 1
    })
    
    if (authResult.code === 0) {
      // 2. 设置密码
      const setPasswordResult = await AccountAPI.setPasswordByAuthToken({
        authToken: authResult.data.authToken,
        password: formData.password
      })
      
      if (setPasswordResult.code === 0) {
        // 3. 登录
        const loginResult = await AccountAPI.phoneLoginByPassword({
          phone: formData.phone,
          accountType: 1,
          password: formData.password
        })
        
        if (loginResult.code === 0) {
          // 保存token和用户信息
          setToken(loginResult.data.token)
          setUserInfo(loginResult.data.userInfo)
          
          uni.showToast({
            title: '注册成功',
            icon: 'success'
          })
          
          // 延迟跳转
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/views/index'
            })
          }, 1500)
        }
      }
    }
  } catch (error) {
    console.error('注册失败:', error)
    uni.showToast({
      title: error.message || '注册失败，请检查网络连接',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 跳转到登录页
const goToLogin = () => {
  uni.navigateBack()
}

// 页面加载时检查是否已登录
onMounted(() => {
  const token = uni.getStorageSync('user_token')
  if (token) {
    uni.reLaunch({
      url: '/pages/views/index'
    })
  }
})
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

// 背景装饰
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  
  .circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    
    &.circle-1 {
      width: 200rpx;
      height: 200rpx;
      top: 10%;
      right: -50rpx;
    }
    
    &.circle-2 {
      width: 150rpx;
      height: 150rpx;
      top: 60%;
      left: -30rpx;
    }
  }
}

.register-form {
  position: relative;
  z-index: 1;
  padding: 60rpx 40rpx;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

// 标题区域
.title-section {
  text-align: center;
  margin-bottom: 60rpx;
  
  .title {
    font-size: 48rpx;
    font-weight: bold;
    color: #fff;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
    display: block;
    margin-bottom: 20rpx;
  }
  
  .subtitle {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

// 表单区域
.form-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
}

.form-item {
  margin-bottom: 40rpx;
  
  .input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    background: #f8f9fa;
    border-radius: 12rpx;
    padding: 0 20rpx;
    border: 2rpx solid transparent;
    transition: all 0.3s ease;
    
    &:focus-within {
      border-color: #667eea;
      background: #fff;
      box-shadow: 0 0 0 4rpx rgba(102, 126, 234, 0.1);
    }
    
    .icon {
      font-size: 32rpx;
      margin-right: 20rpx;
      color: #666;
    }
    
    .input {
      flex: 1;
      height: 88rpx;
      font-size: 28rpx;
      color: #333;
      background: transparent;
      
      &::placeholder {
        color: #999;
      }
    }
    
    .code-btn {
      height: 60rpx;
      padding: 0 20rpx;
      background: #667eea;
      color: #fff;
      border: none;
      border-radius: 8rpx;
      font-size: 24rpx;
      margin-left: 20rpx;
      
      &.disabled {
        background: #ccc;
        color: #999;
      }
    }
    
    .password-toggle {
      font-size: 32rpx;
      color: #666;
      padding: 10rpx;
      cursor: pointer;
    }
  }
  
  .error-text {
    font-size: 24rpx;
    color: #ff4757;
    margin-top: 10rpx;
    display: block;
  }
}

// 注册按钮
.register-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12rpx;
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 40rpx;
  transition: all 0.3s ease;
  
  &:not(.disabled):active {
    transform: scale(0.98);
  }
  
  &.disabled {
    background: #ccc;
    color: #999;
  }
  
  .loading-text {
    display: flex;
    align-items: center;
    justify-content: center;
    
    &::before {
      content: '';
      width: 20rpx;
      height: 20rpx;
      border: 2rpx solid #fff;
      border-top: 2rpx solid transparent;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-right: 10rpx;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 底部链接
.bottom-links {
  text-align: center;
  
  .link {
    font-size: 26rpx;
    color: #667eea;
    text-decoration: none;
    
    &:active {
      opacity: 0.7;
    }
  }
}
</style> 